<?php
class admin_model_user extends admin_model_base  {
	public function __construct(){
		parent::__construct();
		$this->table = '_users';
	}
	
	public function insert($uid, $username){
		$sql = 'insert ignore into '.$this->table.' values(&uid, &username)';
		$params  = array('uid'=>$uid, 'username'=>$username);
		return $this->admin_db->query($sql, $params);
	}
	
	public function selectList(){
		$sql = "select * from ".$this->table;
		return $this->admin_db->fetchAll($sql);
	}
	
	public function select($id){
		$sql = "select * from ".$this->table." where id=$id";
		return $this->admin_db->fetchRow($sql, $params);
	}
	
	public function remove($id){
		$id = is_array($id)?implode(',',$id):$id;
		$this->admin_db->query('delete from priv_users where uid IN('.$id.')');
		$this->admin_db->query('delete from user_roles where uid IN('.$id.')');
		$this->admin_db->query("DELETE FROM $this->table WHERE id IN($id)");
		return $this->admin_db->query("DELETE FROM cartoon_members WHERE uid IN ($id) ");
//		return $this->admin_db->remove($this->table, $id);
	}
	
	public function selectUserPriv($uid){
		$sql = "select concat(r.app, '_', r.controller, '_', r.action) resource from priv_users p 
inner join _resources r on p.res_id=r.id 
where p.uid=&uid";
		$params = array('uid'=>$uid);
		return $this->admin_db->fetchAll($sql, $params);
	}
	
	public function selectUserRole($uid){
		$sql = "select r.role, u.rid from user_roles u 
inner join _roles r on u.rid = r.id
where u.uid = &uid";
		$params = array('uid'=>$uid);
		return $this->admin_db->fetchAll($sql, $params);
	}
	
	public function cleanRole($uid){
		return $this->admin_db->query('delete from user_roles where uid='.$uid);
	}
	
	public function cleanPriv($uid){
		$this->admin_db->query('delete from priv_users where uid='.$uid);
	}
	
	public function savePriv($uid, $pid){
		$params = array('uid'=>$uid, 'res_id'=>$pid);
		return $this->admin_db->save('priv_users', $params);
	}
	
	public function saveRoles($uid, $rid){
		$params = array('uid'=>$uid, 'rid'=>$rid);
		return $this->admin_db->save('user_roles', $params);
	}
	
	public function has($username){
		$sql = "select * from ".$this->table." where username=&username";
		$params = array('username'=>$username);
		return $this->admin_db->fetchRow($sql, $params);
	}
}